package com.suke.controller;

import com.suke.bean.Article;
import com.suke.bean.ResultVo;
import com.suke.bean.User;
import com.suke.service.VoteSysService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class VoteSysController {

    @Autowired
    private VoteSysService voteSysService;

    //用户登录
    @RequestMapping("/login")
    public String login(User user, HttpSession session) {
        user = voteSysService.login(user);
        session.setAttribute("user", user);
        //forward:list 内部方法跳转
        return "forward:list";
    }

    //保存文章
    @RequestMapping("/saveArticle")
    public String saveArticle(Article article, HttpSession session) {
        User user = (User) session.getAttribute("user");
        voteSysService.punish(article, user);
        return "forward:list";
    }


    //登出
    @RequestMapping("/logOut")
    public String logOut(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/login.jsp";
    }

    //查询所有数据
    @RequestMapping("/list")
    public String list(Model model, @RequestParam(defaultValue = "time") String type, @RequestParam(defaultValue = "asc") String ascOrDesc) {
        List<Article> articles = null;
        if ("time".equals(type)) {
            articles = voteSysService.orderByTime(ascOrDesc);
        } else {
            articles = voteSysService.orderByVotes(ascOrDesc);
        }

        model.addAttribute("articles", articles);
        return "index";
    }

    //异步投票
    @RequestMapping("/vote")
    @ResponseBody
    public ResultVo vote(String aid, HttpSession session) {
        ResultVo resultVo = new ResultVo();
        User user = (User) session.getAttribute("user");
        boolean voteOk = voteSysService.vote(aid, user.getUid());
        if (voteOk) {
            resultVo.setOk(true);
        } else {
            resultVo.setMessage("不能重复投票");
        }
        return resultVo;
    }
}
